package web.servlet;

import domain.Cart;
import domain.CartItem;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class UpdateCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        String quantityStr = req.getParameter("quantity");
        String itemIdStr = req.getParameter("itemId");
        Iterator<CartItem> cartItems = cart.getAllCartItems();

        while(cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                String quantityString = req.getParameter(itemId);
                int quantity;
                if(itemId.equals(itemIdStr)) {
                    quantity = Integer.parseInt(quantityStr);
                } else {
                    quantity = Integer.parseInt(quantityString);
                }

                cart.setQuantityByItemId(itemId,quantity);
                if(quantity < 1) {
                    cartItems.remove();
                }
            } catch (Exception e) {
            }
        }
//        由于使用ajax，此处不需要服务器将整个页面重新进行跳转，只要回传一些数据信息即可
//        req.getRequestDispatcher(CART_FORM).forward(req,resp);

        PrintWriter out = resp.getWriter();
        out.println(cart.getSubTotal());
    }
}
